﻿using System;
using System.ComponentModel;
using System.IO;
using Esponce.QRCode;
using Microsoft.Win32;

namespace Esponce.Models
{
	public class TrackStatisticsViewModel : INotifyPropertyChanged
	{
		#region Public properties
		public string QRCodeId
		{
			get
			{
				return this.qrcodeId;
			}
			set
			{
				if (this.qrcodeId != value)
				{
					this.qrcodeId = value;
					OnPropertyChanged("QRCodeId");
				}
			}
		}
		private string qrcodeId;
		
		public int FormatIndex
		{
			get
			{
				return this.formatIndex;
			}
			set
			{
				if (this.formatIndex != value)
				{
					this.formatIndex = value;
					OnPropertyChanged("FormatIndex");
					OnPropertyChanged("Format");
					OnPropertyChanged("FileExtension");
				}
			}
		}
		private int formatIndex;

		public ExportFormat Format
		{
			get
			{
				switch (this.FormatIndex)
				{
					case 0:
						return ExportFormat.CSV;

					case 1:
						return ExportFormat.XLS;

					case 2:
						return ExportFormat.XML;

					case 3:
						return ExportFormat.JSON;
				}

				return ExportFormat.CSV;
			}
		}

		public string FileExtension
		{
			get
			{
				switch (this.Format)
				{
					default:
					case ExportFormat.CSV:
						return "csv";

					case ExportFormat.XLS:
						return "xls";

					case ExportFormat.XML:
						return "xml";

					case ExportFormat.JSON:
						return "json";
				}
			}
		}

		public bool IsLoading
		{
			get
			{
				return this.isLoading;
			}
			set
			{
				if (this.isLoading != value)
				{
					this.isLoading = value;
					OnPropertyChanged("IsLoading");
				}
			}
		}
		private bool isLoading;
		#endregion

		#region Public methods
		public void Export()
		{
			try
			{
				SaveFileDialog dialog = new SaveFileDialog();
				dialog.Filter = string.Format("Statistics (*.{0})|*.{0}", this.FileExtension);
				dialog.DefaultExt = "*." + this.FileExtension;
				dialog.FileName = "output";

				if (dialog.ShowDialog() != true)
				{
					return;
				}

				string path = dialog.FileName;

				//Start the loading animation for better UX
				this.IsLoading = true;

				var client = App.ViewModel.CreateClient();
				App.Logger.WriteLine("GET " + client.UriBuilder.BuildTrackExportUrl(this.Format));

				client.GetTrackStatisticsCompleted += (sender, e) =>
				{
					//Stop the loading animation
					this.IsLoading = false;

					try
					{
						if (e.Error != null)
						{
							throw e.Error;
						}

						if (e.Stream == null)
						{
							throw new Exception("Stream is missing!");
						}

						using (var file = File.Open(path, FileMode.Create, FileAccess.Write))
						{
							int length = 0;
							byte[] buffer = new byte[1024];
							while ((length = e.Stream.Read(buffer, 0, 1024)) != 0)
							{
								file.Write(buffer, 0, length);
							}
						}

						App.Logger.WriteLine("Statistics export completed: " + path);
					}
					catch (Exception ex)
					{
						//Report error to the console
						App.Logger.Log(ex);
					}
				};
				client.GetTrackStatisticsAsync(this.QRCodeId, this.Format);
			}
			catch (Exception ex)
			{
				App.Logger.Log(ex);
			}
		}
		#endregion

		#region INotifyPropertyChanged Members
		public event PropertyChangedEventHandler PropertyChanged;
		protected virtual void OnPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}
		#endregion
	}
}
